import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import {
  Toast
} from 'vant'
import store from '@/store'

const login = () => import('@/views/login')
const layout = () => import('@/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const mine = () => import('@/views/mine')
const edit = () => import('@/views/mine/edit')
const news = () => import('@/views/news')
const chat = () => import('@/views/mine/chat')
const search = () => import('@/views/serarch')
const result = () => import('@/views/serarch/result')

const routes = [{
    path: '',
    redirect: '/layout/home'
  },
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: chat,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'news',
    path: '/news',
    component: news
  },
  {
    name: 'result',
    path: '/search/result',
    component: result
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [{
        name: 'home',
        path: 'home',
        component: home,
        meta: {
          needKeep: true
        }
      },
      {
        name: 'ask',
        path: 'ask',
        component: ask
      },
      {
        name: 'video',
        path: 'video',
        component: video
      },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      },
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {

  // 判断去的页面是不是需要登录的页面
  // 需要先给路由打上标签
  if (to.meta.needLogin) {
    // 证明是需要登录的页面 
    // 如何判断有没有登录？
    if (store.state.tokenObj.token) {

      next()
    } else {
      // 代表没登录，打回登录页
      // 页就是放行到登录页
      // 弹出一个轻提示
      Toast.fail('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    next()
  }

})


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
export default router